package com.it.springboot_day01demo.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.it.springboot_day01demo.bean.User;
import com.it.springboot_day01demo.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@Controller
//@RequestMapping()
//@RestController//@RestController约等于@Controller+@Responsebody:返回JSON类型的字段
//使用了@RestController注解，所有的Controller方法返回值类型为String，返回的不是页面，也就是说所有的Controller方法返回的都是json
public class UserController {
    @Resource
    private UserService userService;
    @RequestMapping(value="selectUserList.do",produces="application/json; charset=utf-8")
    public String selectUserList(Model model, @RequestParam(defaultValue = "1") int pageNum){
        //通过PageHelper调用startPage方法设置查询的页码和每页查询条数
        PageHelper.startPage(pageNum,3);
        //开始查询
        List<User> users = userService.selectAllUserList();
        //将查询的结果以及分页的相关数据封装到pageInfo的对象中
        PageInfo pageInfo = new PageInfo(users);
        model.addAttribute("pageInfo",pageInfo);
        return "list";
    }

    /*@RequestMapping("/updateUserById.do")
    public String updateUserById(){
        User user = new User();
        user.setId(6);
        user.setEname("娅莫拉苏娜丹妮谢莉红");
        int result = userService.updateUserById(user);
        if(result>0){
            return "success!";
        }else{
            return "fall";
        }

    }*/

    @RequestMapping("deleteUserById.do")
    public String deleteUserById(){
        User user = new User();
        int usid = 10;
        int result = userService.deleteUserById(usid);
        if(result>0){
            return "success!";
        }else{
            return "fall";
        }
    }

    @RequestMapping("selectUserById.do")
    public String selectUserById(int id,Model model){
        User user = userService.selectUserById(id);
        model.addAttribute("user",user);
        return "update";
    }

    @RequestMapping("updateUserById.do")
    public String updateUserById(User user){
        int result = userService.updateUserById(user);
        if(result > 0){
            return "redirect:selectUserList.do";
        }else{
            return "update";
        }
    }

    @RequestMapping("/toIndex2.do")
    public String toIindex2(){
        return "index2";
    }
}
